package cc.eddic.pratice.programmingparadigms.nginxlog.impl;

import cc.eddic.pratice.programmingparadigms.nginxlog.LogItem;
import cc.eddic.pratice.programmingparadigms.nginxlog.LogItemParser;
import cc.eddic.pratice.programmingparadigms.nginxlog.NginxLogItem;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Optional;

public class LogItemParserTyqImpl implements LogItemParser {
    @Override
    public Optional<LogItem> parse(NginxLogItem nginxLogItem) {
        String[] requestArray = nginxLogItem.getRequest().split(" ");
        if (requestArray.length != 3) {
            return Optional.empty();
        }
        String URL = requestArray[1];
        String path;
        if (!URL.contains("?")) {
            path = URL;
        } else {
            path = URL.substring(URL.indexOf("/"), URL.indexOf("?"));
        }
        return Optional.of(new LogItem(nginxLogItem.getIp(), LocalDateTime.now(), requestArray[0], path, new HashMap<>(), requestArray[2], Integer.parseInt(nginxLogItem.getStatus()), Long.parseLong(nginxLogItem.getBytes()), nginxLogItem.getReferer(), nginxLogItem.getUserAgent()));
    }
}
